#include "timer.h"
#include <boost/bind.hpp>

Timer::Timer(IOService &service,
             unsigned int owner,
             unsigned int id,
             unsigned long elapse,
             unsigned int repeat) :
    m_impl(service),
    m_owner(owner),
    m_id(id),
    m_elapse(elapse),
    m_repeat(repeat)
{

}

Timer::~Timer()
{
    cancel();
}

void Timer::start(BOOST_ASIO_MOVE_ARG(Notifier) n)
{
    m_impl.expires_from_now(boost::posix_time::milliseconds(m_elapse));

    m_impl.async_wait
            (
                boost::bind
                (
                    &Timer::onTimerout,
                    this,
                    Notifier(n),
                    _1
                )
            );
}

void Timer::cancel()
{
    ErrorCode ec;

    m_impl.cancel(ec);
}

unsigned int Timer::owner() const
{
    return m_owner;
}

unsigned int Timer::id() const
{
    return m_id;
}

unsigned long Timer::elapse() const
{
    return m_elapse;
}

unsigned int Timer::repeat() const
{
    return m_repeat;
}

void Timer::onTimerout(Notifier n, const ErrorCode &ec)
{
    n(ec.value());
}
